#include "common/pch.h"
#include "map/map.h"

#include <format>

#include <cftf/loger/syslog.h>

#include "dbc/structure.h"
#include "object/object.h"
#include "object/objectmgr.h"
#include "object/objectaccessor.h"
#include "object/player.h"
#include "object/gameobject.h"
#include "object/creature.h"
#include "object/corpse.h"
#include "object/dynamicobject.h"
#include "object/pet.h"
#include "object/item.h"
#include "object/transport.h"
#include "object/camera.h"
#include "object/viewpoint.h"
#include "map/cellimpl.h"
#include "system/grid/ngrid.h"
#include "metadata/metamgr.h"
#include "world/world.h"
#include "map/objectgridloader.h"
#include "map/terrain.h"
#include "map/terrainmgr.h"
#include "mmap/mmapmgr.h"
#include "system/weather.h"
#include "metadata/creatureinfo.h"
#include "map/instance_data.h"
#include "map/map_persistent_state_mgr.h"

#ifdef ENABLE_ELUNA
#include "LuaEngine.h"
#endif /* ENABLE_ELUNA */

Map::~Map()
{
#ifdef ENABLE_ELUNA
    sEluna->OnDestroy(this);
#endif /* ENABLE_ELUNA */

    UnloadAll(true);

    if (!m_scriptSchedule.empty())
    {
        game::script::ScriptMgr::Instance().DecreaseScheduledScriptCount(m_scriptSchedule.size());
    }
    if (m_persistentState)
    {
        m_persistentState->SetUsedByMapState(NULL);          // field pointer can be deleted after this
    }

#ifdef ENABLE_ELUNA
    if (Instanceable())
    {
        sEluna->FreeInstanceId(GetInstanceId());
    }
#endif /* ENABLE_ELUNA */

    delete i_data;
    i_data = nullptr;
    // unload all local transporters
    for (auto t = i_transports.begin(); t != i_transports.end(); ++t)
    {
        delete* t;
    }
        
    // unload instance specific navigation data
    mmap::MMapMgr::Instance().UnloadMapInstance(m_TerrainData->GetMapId(), GetInstanceId());

    // release reference count
    if (m_TerrainData->Release())
    {
        TerrainManager::Instance().UnloadTerrain(m_TerrainData->GetMapId());
    }
    delete m_weatherSystem;
    m_weatherSystem = nullptr;
}

void Map::LoadMapAndVMap(int gx, int gy)
{
    if (m_bLoadedGrids[gx][gy])
    {
        return;
    }
    if (m_TerrainData->Load(gx, gy))
    {
        m_bLoadedGrids[gx][gy] = true;
    }
}

Map::Map(unsigned int id, time_t expiry, unsigned int InstanceId)
    : i_mapEntry(dbc::MapEntry::GetElement(id)),
    i_id(id), i_InstanceId(InstanceId), m_unloadTimer(0),
    m_VisibleDistance(DEFAULT_VISIBILITY_DISTANCE), m_persistentState(NULL),
    m_activeNonPlayersIter(m_activeNonPlayers.end()),
    i_gridExpiry(expiry),
    m_TerrainData(TerrainManager::Instance().LoadTerrain(id)),
    i_data(nullptr)
{
    m_CreatureGuids.Set(ObjectMgr::Instance().GetFirstTemporaryCreatureLowGuid());
    m_GameObjectGuids.Set(ObjectMgr::Instance().GetFirstTemporaryGameObjectLowGuid());
    for (unsigned int j = 0; j < MAX_NUMBER_OF_GRIDS; ++j)
    {
        for (unsigned int idx = 0; idx < MAX_NUMBER_OF_GRIDS; ++idx)
        {
            // z code
            m_bLoadedGrids[idx][j] = false;
            setNGrid(NULL, idx, j);
        }
    }
    // lets initialize visibility distance for map
    Map::InitVisibilityDistance();


    // add reference for TerrainData object
    m_TerrainData->AddRef();

    m_persistentState = MapPersistentStateManager::Instance().AddPersistentState(i_mapEntry, GetInstanceId(), 0, IsDungeon());
    m_persistentState->SetUsedByMapState(this);

    m_weatherSystem = new game::system::WeatherSystem(this);
    i_transports.clear();

#ifdef ENABLE_ELUNA
    sEluna->OnCreate(this);
#endif /* ENABLE_ELUNA */
}

void Map::InitVisibilityDistance()
{
    // init visibility for continents
    m_VisibleDistance = World::Instance().GetMaxVisibleDistanceOnContinents();
}

// Template specialization of utility methods
template<class T>
void Map::AddToGrid(T* obj, NGridType* grid, Cell const& cell)
{
    (*grid)(cell.CellX(), cell.CellY()).template AddGridObject<T>(obj);
}

template<>
void Map::AddToGrid(battle::object::Player* obj, NGridType* grid, Cell const& cell)
{
    (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj);
}

template<>
void Map::AddToGrid(battle::object::Corpse* obj, NGridType* grid, Cell const& cell)
{
    // add to world object registry in grid
    if (obj->GetType() != CORPSE_BONES)
    {
        (*grid)(cell.CellX(), cell.CellY()).AddWorldObject(obj);
    }
    // add to grid object store
    else
    {
        (*grid)(cell.CellX(), cell.CellY()).AddGridObject(obj);
    }
}

template<>
void Map::AddToGrid(battle::object::Creature* obj, NGridType* grid, Cell const& cell)
{
    // add to world object registry in grid
    if (obj->IsPet())
    {
        (*grid)(cell.CellX(), cell.CellY()).AddWorldObject<battle::object::Creature>(obj);
        obj->SetCurrentCell(cell);
    }
    // add to grid object store
    else
    {
        (*grid)(cell.CellX(), cell.CellY()).AddGridObject<battle::object::Creature>(obj);
        obj->SetCurrentCell(cell);
    }
}

template<class T>
void Map::RemoveFromGrid(T* obj, NGridType* grid, Cell const& cell)
{
    (*grid)(cell.CellX(), cell.CellY()).template RemoveGridObject<T>(obj);
}

template<>
void Map::RemoveFromGrid(battle::object::Player* obj, NGridType* grid, Cell const& cell)
{
    (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj);
}

template<>
void Map::RemoveFromGrid(battle::object::Corpse* obj, NGridType* grid, Cell const& cell)
{
    // remove from world object registry in grid
    if (obj->GetType() != CORPSE_BONES)
    {
        (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject(obj);
    }
    // remove from grid object store
    else
    {
        (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject(obj);
    }
}

template<>
void Map::RemoveFromGrid(battle::object::Creature* obj, NGridType* grid, Cell const& cell)
{
    // remove from world object registry in grid
    if (obj->IsPet())
    {
        (*grid)(cell.CellX(), cell.CellY()).RemoveWorldObject<battle::object::Creature>(obj);
    }
    // remove from grid object store
    else
    {
        (*grid)(cell.CellX(), cell.CellY()).RemoveGridObject<battle::object::Creature>(obj);
    }
}

void Map::DeleteFromWorld(battle::object::Player* pl)
{
#if 0
    sObjectAccessor.RemoveObject(pl);
#endif
    delete pl;
}

void Map::EnsureGridCreated(const GridPair& p)
{
    if (!getNGrid(p.x_coord, p.y_coord))
    {
        setNGrid(new NGridType(p.x_coord * MAX_NUMBER_OF_GRIDS + p.y_coord, p.x_coord, p.y_coord, i_gridExpiry, mt::MetaMgr::Instance().GetConf()->At("MangosdConf.GridUnload")->AsXValue().Get<int>() != 0),
            p.x_coord, p.y_coord);

        // build a linkage between this map and NGridType
        buildNGridLinkage(getNGrid(p.x_coord, p.y_coord));
        getNGrid(p.x_coord, p.y_coord)->SetGridState(game::system::grid::GRID_STATE_IDLE);

        // z coord
        int gx = (MAX_NUMBER_OF_GRIDS - 1) - p.x_coord;
        int gy = (MAX_NUMBER_OF_GRIDS - 1) - p.y_coord;

        if (!m_bLoadedGrids[gx][gy])
        {
            LoadMapAndVMap(gx, gy);
        }
    }
}

void Map::EnsureGridLoadedAtEnter(const Cell& cell, battle::object::Player* player)
{
    NGridType* grid;
    if (EnsureGridLoaded(cell))
    {
        grid = getNGrid(cell.GridX(), cell.GridY());

        if (player)
        {
            cftf::loger::SysLog::Instance().Deubg(std::format("Player {} enter cell[{},{}] triggers of loading grid[{},{}] on map {}", player->GetName(), cell.CellX(), cell.CellY(), cell.GridX(), cell.GridY(), i_id));
        }
        else
        {
            cftf::loger::SysLog::Instance().Deubg(std::format("Active object nearby triggers of loading grid [{},{}] on map {}", cell.GridX(), cell.GridY(), i_id));
        }

        ResetGridExpiry(*getNGrid(cell.GridX(), cell.GridY()), 0.1f);
        grid->SetGridState(game::system::grid::GRID_STATE_ACTIVE);
    }
    else
    {
        grid = getNGrid(cell.GridX(), cell.GridY());
    }

    if (player)
    {
        AddToGrid(player, grid, cell);
    }
}

bool Map::EnsureGridLoaded(const Cell& cell)
{
    EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
    NGridType* grid = getNGrid(cell.GridX(), cell.GridY());

    CFT_ASSERT(grid != NULL);
    if (!isGridObjectDataLoaded(cell.GridX(), cell.GridY()))
    {
        // it's important to set it loaded before loading!
        // otherwise there is a possibility of infinity chain (grid loading will be called many times for the same grid)
        // possible scenario:
        // active object A(loaded with loader.LoadN call and added to the  map)
        // summons some active object B, while B added to map grid loading called again and so on..
        setGridObjectDataLoaded(true, cell.GridX(), cell.GridY());
        ObjectGridLoader loader(*grid, this, cell);
        loader.LoadN();

        // Add resurrectable corpses to world object list in grid
#if 0
        sObjectAccessor.AddCorpsesToGrid(GridPair(cell.GridX(), cell.GridY()), (*grid)(cell.CellX(), cell.CellY()), this);
#endif
        return true;
    }

    return false;
}

void Map::ForceLoadGrid(float x, float y)
{
    if (!IsLoaded(x, y))
    {
        CellPair p = map::grid::ComputeCellPair(x, y);
        Cell cell(p);
        EnsureGridLoadedAtEnter(cell);
        getNGrid(cell.GridX(), cell.GridY())->setUnloadExplicitLock(true);
    }
}

bool Map::Add(battle::object::Player* player)
{
    m_mapRefManager.add_tail(player->GetPlayerMapEntry());
    player->SetMap(this);

    // update player state for other player and visa-versa
    CellPair p = map::grid::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
    Cell cell(p);
    EnsureGridLoadedAtEnter(cell, player);
    player->AddToWorld();

    SendInitSelf(player);
    SendInitTransports(player);

    NGridType* grid = getNGrid(cell.GridX(), cell.GridY());
    player->GetViewPoint().Event_AddedToWorld(&(*grid)(cell.CellX(), cell.CellY()));
    UpdateObjectVisibility(player, cell, p);

#ifdef ENABLE_ELUNA
    sEluna->OnMapChanged(player);
    sEluna->OnPlayerEnter(this, player);
#endif /* ENABLE_ELUNA */

    if (i_data)
    {
        i_data->OnPlayerEnter(player);
    }
    return true;
}

template<class T>
void Map::Add(T* obj)
{
    CFT_ASSERT(obj);

    CellPair p = map::grid::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
    if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
    {
        cftf::loger::SysLog::Instance().Error(std::format("Map::Add: Object (GUID: {} TypeId: {}) have invalid coordinates X:{} Y:{} grid cell [{}:{}]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord));
        return;
    }

    obj->SetMap(this);

    Cell cell(p);
    if (obj->IsActiveObject())
    {
        EnsureGridLoadedAtEnter(cell);
    }
    else
    {
        EnsureGridCreated(GridPair(cell.GridX(), cell.GridY()));
    }

    NGridType* grid = getNGrid(cell.GridX(), cell.GridY());
    CFT_ASSERT(grid != NULL);

    AddToGrid(obj, grid, cell);
    obj->AddToWorld();

    if (obj->IsActiveObject())
    {
        AddToActive(obj);
    }

    cftf::loger::SysLog::Instance().Error(std::format("{} enters grid[{},{}]", obj->GetGuidStr().c_str(), cell.GridX(), cell.GridY()));

    obj->GetViewPoint().Event_AddedToWorld(&(*grid)(cell.CellX(), cell.CellY()));
    obj->SetAsNewObject(true);
    UpdateObjectVisibility(obj, cell, p);
    obj->SetAsNewObject(false);
}

#if 0
void Map::MessageBroadcast(Player const* player, WorldPacket* msg, bool to_self)
{
    CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());

    if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
    {
        sLog.outError("Map::MessageBroadcast: Player (GUID: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", player->GetGUIDLow(), player->GetPositionX(), player->GetPositionY(), p.x_coord, p.y_coord);
        return;
    }

    Cell cell(p);
    cell.SetNoCreate();

    if (!loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)))
    {
        return;
    }

    MaNGOS::MessageDeliverer post_man(*player, msg, to_self);
    TypeContainerVisitor<MaNGOS::MessageDeliverer, WorldTypeMapContainer > message(post_man);
    cell.Visit(p, message, *this, *player, GetVisibilityDistance());
}

void Map::MessageBroadcast(WorldObject const* obj, WorldPacket* msg)
{
    CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());

    if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
    {
        sLog.outError("Map::MessageBroadcast: Object (GUID: %u TypeId: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
        return;
    }

    Cell cell(p);
    cell.SetNoCreate();

    if (!loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)))
    {
        return;
    }

    // TODO: currently on continents when Visibility.Distance.InFlight > Visibility.Distance.Continents
    // we have alot of blinking mobs because monster move packet send is broken...
    MaNGOS::ObjectMessageDeliverer post_man(msg);
    TypeContainerVisitor<MaNGOS::ObjectMessageDeliverer, WorldTypeMapContainer > message(post_man);
    cell.Visit(p, message, *this, *obj, GetVisibilityDistance());
}

void Map::MessageDistBroadcast(Player const* player, WorldPacket* msg, float dist, bool to_self, bool own_team_only)
{
    CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());

    if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
    {
        sLog.outError("Map::MessageBroadcast: Player (GUID: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", player->GetGUIDLow(), player->GetPositionX(), player->GetPositionY(), p.x_coord, p.y_coord);
        return;
    }

    Cell cell(p);
    cell.SetNoCreate();

    if (!loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)))
    {
        return;
    }

    MaNGOS::MessageDistDeliverer post_man(*player, msg, dist, to_self, own_team_only);
    TypeContainerVisitor<MaNGOS::MessageDistDeliverer, WorldTypeMapContainer > message(post_man);
    cell.Visit(p, message, *this, *player, dist);
}

void Map::MessageDistBroadcast(WorldObject const* obj, WorldPacket* msg, float dist)
{
    CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());

    if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
    {
        sLog.outError("Map::MessageBroadcast: Object (GUID: %u TypeId: %u) have invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
        return;
    }

    Cell cell(p);
    cell.SetNoCreate();

    if (!loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)))
    {
        return;
    }

    MaNGOS::ObjectMessageDistDeliverer post_man(*obj, msg, dist);
    TypeContainerVisitor<MaNGOS::ObjectMessageDistDeliverer, WorldTypeMapContainer > message(post_man);
    cell.Visit(p, message, *this, *obj, dist);
}
#endif

bool Map::loaded(const GridPair& p) const
{
    return (getNGrid(p.x_coord, p.y_coord) && isGridObjectDataLoaded(p.x_coord, p.y_coord));
}

#if 0
void Map::VisitNearbyCellsOf(WorldObject* obj,
    TypeContainerVisitor<MaNGOS::ObjectUpdater, GridTypeMapContainer>& gridVisitor,
    TypeContainerVisitor<MaNGOS::ObjectUpdater, WorldTypeMapContainer>& worldVisitor)
{
    if (!obj->IsPositionValid())
    {
        return;
    }

    // lets update mobs/objects in ALL visible cells around player!
    CellArea area = Cell::CalculateCellArea(obj->GetPositionX(), obj->GetPositionY(), GetVisibilityDistance());

    for (unsigned int x = area.low_bound.x_coord; x <= area.high_bound.x_coord; ++x)
    {
        for (unsigned int y = area.low_bound.y_coord; y <= area.high_bound.y_coord; ++y)
        {
            // marked cells are those that have been visited
            // don't visit the same cell twice
            unsigned int cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
            if (!isCellMarked(cell_id))
            {
                markCell(cell_id);
                CellPair pair(x, y);
                Cell cell(pair);
                cell.SetNoCreate();
                Visit(cell, gridVisitor);
                Visit(cell, worldVisitor);
            }
        }
    }
}
#endif

void Map::Update(const unsigned int& t_diff)
{
    m_dyn_tree.update(t_diff);
#if 0
    /// update worldsessions for existing players
    for (m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
    {
        Player* plr = m_mapRefIter->getSource();
        if (plr && plr->IsInWorld())
        {
            WorldSession* pSession = plr->GetSession();
            MapSessionFilter updater(pSession);

            pSession->Update(updater);
        }
    }

    /// update players at tick
    for (m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
    {
        Player* plr = m_mapRefIter->getSource();
        if (plr && plr->IsInWorld())
        {
            WorldObject::UpdateHelper helper(plr);
            helper.Update(t_diff);
        }
    }

    /// update local transports
    for (std::set<Transport*>::iterator t = i_transports.begin(); t != i_transports.end(); ++t)
    {
        WorldObject::UpdateHelper helper(*t);
        helper.Update(t_diff);
    }

    /// update active cells around players and active objects
    resetMarkedCells();

    MaNGOS::ObjectUpdater updater(t_diff);
    // for creature
    TypeContainerVisitor<MaNGOS::ObjectUpdater, GridTypeMapContainer  > grid_object_update(updater);
    // for pets
    TypeContainerVisitor<MaNGOS::ObjectUpdater, WorldTypeMapContainer > world_object_update(updater);

    // the player iterator is stored in the map object
    // to make sure calls to Map::Remove don't invalidate it
    for (m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
    {
        Player* plr = m_mapRefIter->getSource();

        if (!plr || !plr->IsInWorld())
        {
            continue;
        }

        VisitNearbyCellsOf(plr, grid_object_update, world_object_update);

        // Collect and remove references to creatures too far away from player's m_HostileRefManager
        // Combat state will change on next tick, if case
        if (!IsDungeon() && plr->IsInCombat())
        {
            std::vector<Creature*> _removeList;
            HostileRefManager& href = plr->GetHostileRefManager();
            HostileReference* ref = href.getFirst();

            while (ref)
            {
                if (Unit* unit = ref->getSource()->getOwner())
                    if (unit->ToCreature() && unit->GetMapId() == plr->GetMapId() && !unit->IsWithinDistInMap(plr, GetVisibilityDistance(), false))
                    {
                        _removeList.push_back(unit->ToCreature());
                    }

                ref = ref->next();
            }

            for (std::vector<Creature*>::iterator it = _removeList.begin(); it != _removeList.end(); ++it)
            {
                (*it)->RemoveAurasByCaster(plr->GetObjectGuid());
                (*it)->_removeAttacker(plr);
                (*it)->GetHostileRefManager().deleteReference(plr);

                href.deleteReference(*it);

                VisitNearbyCellsOf(*it, grid_object_update, world_object_update);
            }
        }
    }

    // non-player active objects
    if (!m_activeNonPlayers.empty())
    {
        for (m_activeNonPlayersIter = m_activeNonPlayers.begin(); m_activeNonPlayersIter != m_activeNonPlayers.end();)
        {
            WorldObject* obj = *m_activeNonPlayersIter;

            // step before processing, in this case if Map::Remove remove next object we correctly
            // step to next-next, and if we step to end() then newly added objects can wait next update.
            ++m_activeNonPlayersIter;

            // skip not in world
            if (!obj || !obj->IsInWorld())
            {
                continue;
            }

            VisitNearbyCellsOf(obj, grid_object_update, world_object_update);
        }
    }

    // Send world objects and item update field changes
    SendObjectUpdates();

    // Don't unload grids if it's battleground, since we may have manually added GOs,creatures, those doesn't load from DB at grid re-load !
    // This isn't really bother us, since as soon as we have instanced BG-s, the whole map unloads as the BG gets ended
    if (!IsBattleGround())
    {
        for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end();)
        {
            NGridType* grid = i->getSource();
            GridInfo* info = i->getSource()->getGridInfoRef();
            ++i;                                            // The update might delete the map and we need the next map before the iterator gets invalid
            CFT_ASSERT(grid->GetGridState() >= 0 && grid->GetGridState() < MAX_GRID_STATE);
            sMapMgr.UpdateGridState(grid->GetGridState(), *this, *grid, *info, grid->getX(), grid->getY(), t_diff);
        }
    }

    ///- Process necessary scripts
    if (!m_scriptSchedule.empty())
    {
        ScriptsProcess();
    }

#ifdef ENABLE_ELUNA
    sEluna->OnUpdate(this, t_diff);
#endif /* ENABLE_ELUNA */
#endif
    if (i_data)
    {
        i_data->Update(t_diff);
    }
    m_weatherSystem->UpdateWeathers(t_diff);
}

void Map::Remove(battle::object::Player* player, bool remove)
{

#ifdef ENABLE_ELUNA
    sEluna->OnPlayerLeave(this, player);
#endif /* ENABLE_ELUNA */

    if (i_data)
    {
        i_data->OnPlayerLeave(player);
    }
#if 0
    if (remove)
    {
        player->CleanupsBeforeDelete();
    }
    else
    {
        player->RemoveFromWorld();
    }

    // this may be called during Map::Update
    // after decrement+unlink, ++m_mapRefIter will continue correctly
    // when the first element of the list is being removed
    // nocheck_prev will return the padding element of the RefManager
    // instead of NULL in the case of prev
    if (m_mapRefIter == player->GetMapRef())
    {
        m_mapRefIter = m_mapRefIter->nocheck_prev();
    }
    player->GetMapRef().unlink();
    CellPair p = MaNGOS::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
    if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
    {
        // invalid coordinates
        player->ResetMap();

        if (remove)
        {
            DeleteFromWorld(player);
        }

        return;
    }

    Cell cell(p);

    if (!getNGrid(cell.data.Part.grid_x, cell.data.Part.grid_y))
    {
        sLog.outError("Map::Remove() i_grids was NULL x:%d, y:%d", cell.data.Part.grid_x, cell.data.Part.grid_y);
        return;
    }

    DEBUG_FILTER_LOG(LOG_FILTER_PLAYER_MOVES, "Remove player %s from grid[%u,%u]", player->GetName(), cell.GridX(), cell.GridY());
    NGridType* grid = getNGrid(cell.GridX(), cell.GridY());
    CFT_ASSERT(grid != NULL);

    RemoveFromGrid(player, grid, cell);

    SendRemoveTransports(player);
    UpdateObjectVisibility(player, cell, p);

#ifdef ENABLE_PLAYERBOTS
    if (!player->GetPlayerbotAI())
#endif
        player->ResetMap();
    if (remove)
    {
        DeleteFromWorld(player);
    }
#endif
}

template<class T>
void Map::Remove(T* obj, bool remove)
{
    CellPair p = map::grid::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
    if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
    {
        cftf::loger::SysLog::Instance().Error(std::format("Map::Remove: Object (GUID: {} TypeId:{}) have invalid coordinates X:{} Y:{} grid cell [{}:{}]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord));
        return;
    }

    Cell cell(p);
    if (!loaded(GridPair(cell.data.Part.grid_x, cell.data.Part.grid_y)))
    {
        return;
    }

    cftf::loger::SysLog::Instance().Warning(std::format("Remove object (GUID: {} TypeId:{}) from grid[{},{}]", obj->GetGUIDLow(), obj->GetTypeId(), (unsigned int)cell.data.Part.grid_x, (unsigned int)cell.data.Part.grid_y));
    NGridType* grid = getNGrid(cell.GridX(), cell.GridY());
    CFT_ASSERT(grid != NULL);

    if (obj->IsActiveObject())
    {
        RemoveFromActive(obj);
    }

    if (remove)
    {
        obj->CleanupsBeforeDelete();
    }
    else
    {
        obj->RemoveFromWorld();
    }

    UpdateObjectVisibility(obj, cell, p);                   // i think will be better to call this function while object still in grid, this changes nothing but logically is better(as for me)
    RemoveFromGrid(obj, grid, cell);

    obj->ResetMap();
    if (remove)
    {        
        // if option set then object already saved at this moment
        if (!mt::MetaMgr::Instance().GetConf()->At("MangosdConf.SaveRespawnTimeImmediately")->AsXValue().Get<int>())
        {
            obj->SaveRespawnTime();
        }

        // Note: In case resurrectable corpse and pet its removed from global lists in own destructor
        delete obj;
    }
}

void Map::PlayerRelocation(battle::object::Player* player, float x, float y, float z, float orientation)
{
    CFT_ASSERT(player);

    CellPair old_val = map::grid::ComputeCellPair(player->GetPositionX(), player->GetPositionY());
    CellPair new_val = map::grid::ComputeCellPair(x, y);

    Cell old_cell(old_val);
    Cell new_cell(new_val);
    bool same_cell = (new_cell == old_cell);

    player->Relocate(x, y, z, orientation);

    if (old_cell.DiffGrid(new_cell) || old_cell.DiffCell(new_cell))
    {
        cftf::loger::SysLog::Instance().Info(std::format("Player {} relocation grid[{},{}]cell[{},{}]->grid[{},{}]cell[{},{}]", player->GetName(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY()));

        NGridType* oldGrid = getNGrid(old_cell.GridX(), old_cell.GridY());
        RemoveFromGrid(player, oldGrid, old_cell);
        if (!old_cell.DiffGrid(new_cell))
        {
            AddToGrid(player, oldGrid, new_cell);
        }
        else
        {
            EnsureGridLoadedAtEnter(new_cell, player);
        }

        NGridType* newGrid = getNGrid(new_cell.GridX(), new_cell.GridY());
        player->GetViewPoint().Event_GridChanged(&(*newGrid)(new_cell.CellX(), new_cell.CellY()));
    }

    player->OnRelocated();

    NGridType* newGrid = getNGrid(new_cell.GridX(), new_cell.GridY());
    if (!same_cell && newGrid->GetGridState() != game::system::grid::GRID_STATE_ACTIVE)
    {
        ResetGridExpiry(*newGrid, 0.1f);
        newGrid->SetGridState(game::system::grid::GRID_STATE_ACTIVE);
    }
}

void Map::CreatureRelocation(battle::object::Creature* creature, float x, float y, float z, float ang)
{
    CFT_ASSERT(CheckGridIntegrity(creature, false));

    Cell new_cell(map::grid::ComputeCellPair(x, y));

    // do move or do move to respawn or remove creature if previous all fail
    if (CreatureCellRelocation(creature, new_cell))
    {
        // update pos
        creature->Relocate(x, y, z, ang);
        creature->OnRelocated();
    }
    // if creature can't be move in new cell/grid (not loaded) move it to repawn cell/grid
    // creature coordinates will be updated and notifiers send
    else if (!CreatureRespawnRelocation(creature))
    {
        // ... or unload (if respawn grid also not loaded)
        cftf::loger::SysLog::Instance().Error(std::format("Creature (GUID: {} Entry: {} ) can't be move to unloaded respawn grid.", creature->GetGUIDLow(), creature->GetEntry()));
    }

    CFT_ASSERT(CheckGridIntegrity(creature, true));
}

bool Map::CreatureCellRelocation(battle::object::Creature* c, const Cell& new_cell)
{
    Cell const& old_cell = c->GetCurrentCell();
    if (old_cell.DiffGrid(new_cell))
    {
        if (!c->IsActiveObject() && !loaded(new_cell.gridPair()))
        {
            cftf::loger::SysLog::Instance().Error(std::format("Creature (GUID: {} Entry: {}) attempt move from grid[{},{}]cell[{},{}] to unloaded grid[{},{}]cell[{},{}].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY()));
            return false;
        }
        EnsureGridLoadedAtEnter(new_cell);
    }

    if (old_cell != new_cell)
    {
        cftf::loger::SysLog::Instance().Error(std::format("Creature (GUID: {} Entry: {}) moved in grid[{},{}] from cell[{},{}] to cell[{},{}].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.CellX(), new_cell.CellY()));
        NGridType* oldGrid = getNGrid(old_cell.GridX(), old_cell.GridY());
        NGridType* newGrid = getNGrid(new_cell.GridX(), new_cell.GridY());
        RemoveFromGrid(c, oldGrid, old_cell);
        AddToGrid(c, newGrid, new_cell);
        c->GetViewPoint().Event_GridChanged(&(*newGrid)(new_cell.CellX(), new_cell.CellY()));
    }
    return true;
}

bool Map::CreatureRespawnRelocation(battle::object::Creature* c)
{
    float resp_x, resp_y, resp_z, resp_o;
    c->GetRespawnCoord(resp_x, resp_y, resp_z, &resp_o);

    CellPair resp_val = map::grid::ComputeCellPair(resp_x, resp_y);
    Cell resp_cell(resp_val);

    c->CombatStop();
#if 0
    c->GetMotionMaster()->Clear();

    DEBUG_FILTER_LOG(LOG_FILTER_CREATURE_MOVES, "Creature (GUID: %u Entry: %u) will moved from grid[%u,%u]cell[%u,%u] to respawn grid[%u,%u]cell[%u,%u].", c->GetGUIDLow(), c->GetEntry(), c->GetCurrentCell().GridX(), c->GetCurrentCell().GridY(), c->GetCurrentCell().CellX(), c->GetCurrentCell().CellY(), resp_cell.GridX(), resp_cell.GridY(), resp_cell.CellX(), resp_cell.CellY());
#endif
    // teleport it to respawn point (like normal respawn if player see)
    if (CreatureCellRelocation(c, resp_cell))
    {
        c->Relocate(resp_x, resp_y, resp_z, resp_o);
#if 0
        c->GetMotionMaster()->Initialize();                 // prevent possible problems with default move generators
#endif
        c->OnRelocated();
        return true;
    }
    else
    {
        return false;
    }
}

bool Map::UnloadGrid(const unsigned int& x, const unsigned int& y, bool pForce)
{
    NGridType* grid = getNGrid(x, y);
    CFT_ASSERT(grid != NULL);

    {
        if (!pForce && ActiveObjectsNearGrid(x, y))
        {
            return false;
        }

        cftf::loger::SysLog::Instance().Warning(std::format("Unloading grid[{},{}] for map {}", x, y, i_id));
        ObjectGridUnloader unloader(*grid);

        // Finish remove and delete all creatures with delayed remove before moving to respawn grids
        // Must know real mob position before move
        RemoveAllObjectsInRemoveList();

        // move creatures to respawn grids if this is diff.grid or to remove list
        unloader.MoveToRespawnN();

        // Finish remove and delete all creatures with delayed remove before unload
        RemoveAllObjectsInRemoveList();
        unloader.UnloadN();
        delete getNGrid(x, y);
        setNGrid(NULL, x, y);
    }

    int gx = (MAX_NUMBER_OF_GRIDS - 1) - x;
    int gy = (MAX_NUMBER_OF_GRIDS - 1) - y;

    // unload GridMap - it is reference-countable so will be deleted safely when lockCount < 1
    // also simply set Map's pointer to corresponding GridMap object to NULL
    if (m_bLoadedGrids[gx][gy])
    {
        m_bLoadedGrids[gx][gy] = false;
        m_TerrainData->Unload(gx, gy);
    }

    cftf::loger::SysLog::Instance().Warning(std::format("Unloading grid[{},{}] for map {} finished", x, y, i_id));
    return true;
}


void Map::UnloadAll(bool pForce)
{
#if 0
    for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end();)
    {
        NGridType& grid(*i->getSource());
        ++i;
        UnloadGrid(grid.getX(), grid.getY(), pForce);       // deletes the grid and removes it from the GridRefManager
    }
#endif
}

bool Map::CheckGridIntegrity(battle::object::Creature* c, bool moved) const
{
    Cell const& cur_cell = c->GetCurrentCell();

    CellPair xy_val = map::grid::ComputeCellPair(c->GetPositionX(), c->GetPositionY());
    Cell xy_cell(xy_val);
    if (xy_cell != cur_cell)
    {
        cftf::loger::SysLog::Instance().Error(std::format("Creature (GUIDLow: {}) X: {} Y: {} ({}) in grid[{},{}]cell[{},{}] instead grid[{},{}]cell[{},{}]",
            c->GetGUIDLow(),
            c->GetPositionX(), c->GetPositionY(), (moved ? "final" : "original"),
            cur_cell.GridX(), cur_cell.GridY(), cur_cell.CellX(), cur_cell.CellY(),
            xy_cell.GridX(), xy_cell.GridY(), xy_cell.CellX(), xy_cell.CellY()));
        return true;                                        // not crash at error, just output error in debug mode
    }

    return true;
}

const char* Map::GetMapName() const
{
#if 1
    return i_mapEntry ? i_mapEntry->name[World::Instance().GetDefaultDbcLocale()].c_str() : "UNNAMEDMAP\x0";
#else
    return i_mapEntry ? i_mapEntry->name[World::Instance().GetDefaultDbcLocale()] : "UNNAMEDMAP\x0";
#endif
}

void Map::UpdateObjectVisibility(battle::object::WorldObject* obj, Cell cell, CellPair cellpair)
{
    cell.SetNoCreate();
#if 0
    MaNGOS::VisibleChangesNotifier notifier(*obj);
    cell.Visit(cellpair, player_notifier, *this, *obj, GetVisibilityDistance());
    TypeContainerVisitor<MaNGOS::VisibleChangesNotifier, WorldTypeMapContainer > player_notifier(notifier);
#endif
}

void Map::SendInitSelf(battle::object::Player* player)
{
    cftf::loger::SysLog::Instance().Info(std::format("Creating player data for himself {}", player->GetGUIDLow()));

#if 0
    UpdateData data;

    bool hasTransport = false;

    // attach to player data current transport data
    if (Transport* transport = player->GetTransport())
    {
        hasTransport = true;
        transport->BuildCreateUpdateBlockForPlayer(&data, player);
    }

    // build data for self presence in world at own client (one time for map)
    player->BuildCreateUpdateBlockForPlayer(&data, player);

    // build other passengers at transport also (they always visible and marked as visible and will not send at visibility update at add to map
    if (Transport* transport = player->GetTransport())
    {
        for (UnitSet::const_iterator itr = transport->GetPassengers().begin(); itr != transport->GetPassengers().end(); ++itr)
        {
            if (player != (*itr) && player->HaveAtClient(*itr))
            {
                hasTransport = true;
                (*itr)->BuildCreateUpdateBlockForPlayer(&data, player);
            }
        }
    }

    WorldPacket packet;
    data.BuildPacket(&packet, hasTransport);
    player->GetSession()->SendPacket(&packet);
#endif
}

void Map::SendInitTransports(battle::object::Player* player)
{
#if 0
    // Send out global transports
    MapManager::TransportMap& tmap = sMapMgr.m_TransportsByMap;

    if (tmap.find(player->GetMapId()) != tmap.end())
    {
        MapManager::TransportSet& tset = tmap[player->GetMapId()];

        UpdateData transData;
        bool hasTransport = false;

        for (MapManager::TransportSet::const_iterator i = tset.begin(); i != tset.end(); ++i)
        {
            // send data for current transport in other place
            if ((*i) != player->GetTransport() && (*i)->GetMapId() == i_id)
            {
                hasTransport = true;
                (*i)->BuildCreateUpdateBlockForPlayer(&transData, player);
            }
        }

        WorldPacket packet;
        transData.BuildPacket(&packet, hasTransport);
        player->GetSession()->SendPacket(&packet);
    }

    // Now send out local transports
    if (i_transports.size() != 0)
    {
        UpdateData transData;
        bool hasTransport = false;

        for (MapManager::TransportSet::const_iterator i = i_transports.begin(); i != i_transports.end(); ++i)
        {
            // send data for current transport in other place
            if ((*i) != player->GetTransport() && (*i)->GetMapId() == i_id)
            {
                hasTransport = true;
                (*i)->BuildCreateUpdateBlockForPlayer(&transData, player);
            }
        }

        WorldPacket packet;
        transData.BuildPacket(&packet, hasTransport);
        player->GetSession()->SendPacket(&packet);
    }
#endif
}

void Map::SendRemoveTransports(battle::object::Player* player)
{
#if 0
    // Global transports
    MapManager::TransportMap& tmap = sMapMgr.m_TransportsByMap;

    if (tmap.find(player->GetMapId()) != tmap.end())
    {
        UpdateData transData;
        MapManager::TransportSet& tset = tmap[player->GetMapId()];

        // except used transport
        for (MapManager::TransportSet::const_iterator i = tset.begin(); i != tset.end(); ++i)
            if ((*i) != player->GetTransport() && (*i)->GetMapId() != i_id)
            {
                (*i)->BuildOutOfRangeUpdateBlock(&transData);
            }

        WorldPacket packet;
        transData.BuildPacket(&packet);
        player->GetSession()->SendPacket(&packet);
    }

    // Local transports
    if (i_transports.size() != 0)
    {
        UpdateData transData;

        // except used transport
        for (MapManager::TransportSet::const_iterator i = i_transports.begin(); i != i_transports.end(); ++i)
            if ((*i) != player->GetTransport() && (*i)->GetMapId() != i_id)
            {
                (*i)->BuildOutOfRangeUpdateBlock(&transData);
            }

        WorldPacket packet;
        transData.BuildPacket(&packet);
        player->GetSession()->SendPacket(&packet);
    }
#endif
}

inline void Map::setNGrid(NGridType* grid, unsigned int x, unsigned int y)
{
    if (x >= MAX_NUMBER_OF_GRIDS || y >= MAX_NUMBER_OF_GRIDS)
    {
        cftf::loger::SysLog::Instance().Warning(std::format("map::setNGrid() Invalid grid coordinates found: {}, {}!", x, y));
        CFT_ASSERT(false);
    }
    i_grids[x][y] = grid;
}

void Map::AddObjectToRemoveList(battle::object::WorldObject* obj)
{
#if 0
    CFT_ASSERT(obj->GetMapId() == GetId() && obj->GetInstanceId() == GetInstanceId());

#ifdef ENABLE_ELUNA
    if (Creature* creature = obj->ToCreature())
    {
        sEluna->OnRemove(creature);
    }
    else if (GameObject* gameobject = obj->ToGameObject())
    {
        sEluna->OnRemove(gameobject);
    }
#endif /* ENABLE_ELUNA */
#endif
    obj->CleanupsBeforeDelete();                            // remove or simplify at least cross referenced links

    i_objectsToRemove.insert(obj);
    // DEBUG_LOG("Object (GUID: %u TypeId: %u ) added to removing list.",obj->GetGUIDLow(),obj->GetTypeId());
}

void Map::RemoveAllObjectsInRemoveList()
{
    if (i_objectsToRemove.empty())
    {
        return;
    }

    // DEBUG_LOG("Object remover 1 check.");
    while (!i_objectsToRemove.empty())
    {
        battle::object::WorldObject* obj = *i_objectsToRemove.begin();
        i_objectsToRemove.erase(i_objectsToRemove.begin());

        switch (obj->GetTypeId())
        {
        case TYPEID_CORPSE:
        {
            // ??? WTF
            battle::object::Corpse* corpse = GetCorpse(obj->GetObjectGuid());
            if (!corpse)
            {
                cftf::loger::SysLog::Instance().Error(std::format("Try delete corpse/bones {} that not in map", obj->GetGUIDLow()));
            }
            else
            {
                Remove(corpse, true);
            }
            break;
        }
        case TYPEID_DYNAMICOBJECT:
            Remove((battle::object::DynamicObject*)obj, true);
            break;
        case TYPEID_GAMEOBJECT:
            Remove((battle::object::GameObject*)obj, true);
            break;
        case TYPEID_UNIT:
            Remove((battle::object::Creature*)obj, true);
            break;
        default:
            cftf::loger::SysLog::Instance().Error(std::format("Non-grid object (TypeId: {}) in grid object removing list, ignored.", obj->GetTypeId()));
            break;
        }
    }
    // DEBUG_LOG("Object remover 2 check.");
}

unsigned int Map::GetPlayersCountExceptGMs() const
{
    unsigned int count = 0;
    m_mapRefManager.Traverse<battle::object::Player*>(
        [&count](battle::object::Player* hum) -> bool
        {
            if (hum->isGameMaster()) {
                ++count;
            }
            return true;
        }
    );
    return count;
}

#if 0
void Map::SendToPlayers(WorldPacket const* data) const
{
    for (MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
    {
        itr->getSource()->GetSession()->SendPacket(data);
    }
}

bool Map::SendToPlayersInZone(WorldPacket const* data, unsigned int zoneId) const
{
    bool foundPlayer = false;
    for (MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
    {
        if (itr->getSource()->GetZoneId() == zoneId)
        {
            itr->getSource()->GetSession()->SendPacket(data);
            foundPlayer = true;
        }
    }
    return foundPlayer;
}
#endif

bool Map::ActiveObjectsNearGrid(unsigned int x, unsigned int y) const
{
    CFT_ASSERT(x < MAX_NUMBER_OF_GRIDS);
    CFT_ASSERT(y < MAX_NUMBER_OF_GRIDS);

    CellPair cell_min(x * MAX_NUMBER_OF_CELLS, y * MAX_NUMBER_OF_CELLS);
    CellPair cell_max(cell_min.x_coord + MAX_NUMBER_OF_CELLS, cell_min.y_coord + MAX_NUMBER_OF_CELLS);

    // we must find visible range in cells so we unload only non-visible cells...
    float viewDist = GetVisibilityDistance();
    int cell_range = (int)ceilf(viewDist / SIZE_OF_GRID_CELL) + 1;

    cell_min << cell_range;
    cell_min -= cell_range;
    cell_max >> cell_range;
    cell_max += cell_range;

    if (!m_mapRefManager.Traverse<battle::object::Player*>(
        [&cell_min, &cell_max](battle::object::Player* hum) -> bool
        {
            CellPair p = map::grid::ComputeCellPair(hum->GetPositionX(), hum->GetPositionY());
            if ((cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
                (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord))
            {
                return false;
            }
            return true;
        }
    )) {
        return true;
    }

    for (ActiveNonPlayers::const_iterator iter = m_activeNonPlayers.begin(); iter != m_activeNonPlayers.end(); ++iter)
    {
        battle::object::WorldObject* obj = *iter;

        CellPair p = map::grid::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
        if ((cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
            (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord))
        {
            return true;
        }
    }

    return false;
}

void Map::AddToActive(battle::object::WorldObject* obj)
{
    m_activeNonPlayers.insert(obj);
    Cell cell = Cell(map::grid::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY()));
    EnsureGridLoaded(cell);

    // also not allow unloading spawn grid to prevent creating creature clone at load
    if (obj->GetTypeId() == TYPEID_UNIT)
    {
        battle::object::Creature* c = (battle::object::Creature*)obj;

        if (!c->IsPet() && c->HasStaticDBSpawnData())
        {
            float x, y, z;
            c->GetRespawnCoord(x, y, z);
            GridPair p = map::grid::ComputeGridPair(x, y);
            if (getNGrid(p.x_coord, p.y_coord))
            {
                getNGrid(p.x_coord, p.y_coord)->incUnloadActiveLock();
            }
            else
            {
                GridPair p2 = map::grid::ComputeGridPair(c->GetPositionX(), c->GetPositionY());
                cftf::loger::SysLog::Instance().Error(std::format("Active creature (GUID: {} Entry: {}) added to grid[{},{}] but spawn grid[{},{}] not loaded.",
                    c->GetGUIDLow(), c->GetEntry(), p.x_coord, p.y_coord, p2.x_coord, p2.y_coord));
            }
        }
    }
}

void Map::RemoveFromActive(battle::object::WorldObject* obj)
{
    // Map::Update for active object in proccess
    if (m_activeNonPlayersIter != m_activeNonPlayers.end())
    {
        ActiveNonPlayers::iterator itr = m_activeNonPlayers.find(obj);
        if (itr == m_activeNonPlayersIter)
        {
            ++m_activeNonPlayersIter;
        }

        if (itr != m_activeNonPlayers.end())
        {
            m_activeNonPlayers.erase(itr);
        }
    }
    else
    {
        m_activeNonPlayers.erase(obj);
    }

    // also allow unloading spawn grid
    if (obj->GetTypeId() == TYPEID_UNIT)
    {
        battle::object::Creature* c = (battle::object::Creature*)obj;

        if (!c->IsPet() && c->HasStaticDBSpawnData())
        {
            float x, y, z;
            c->GetRespawnCoord(x, y, z);
            GridPair p = map::grid::ComputeGridPair(x, y);
            if (getNGrid(p.x_coord, p.y_coord))
            {
                getNGrid(p.x_coord, p.y_coord)->decUnloadActiveLock();
            }
            else
            {
                GridPair p2 = map::grid::ComputeGridPair(c->GetPositionX(), c->GetPositionY());
                cftf::loger::SysLog::Instance().Error(std::format("Active creature (GUID: {} Entry: {}) removed from grid[{},{}] but spawn grid[{},{}] not loaded.",
                    c->GetGUIDLow(), c->GetEntry(), p.x_coord, p.y_coord, p2.x_coord, p2.y_coord));
            }
        }
    }
}

void Map::CreateInstanceData(bool load)
{
    if (i_data != nullptr)
    {
        return;
    }
#if 0
#ifdef ENABLE_ELUNA
    i_data = sEluna->GetInstanceData(this);
#endif /* ENABLE_ELUNA */

    unsigned int i_script_id = 0;
    if (!i_data)
    {
        i_script_id = GetScriptId();

        if (!i_script_id)
        {
            return;
        }

        i_data = sScriptMgr.CreateInstanceData(this);
        if (!i_data)
        {
            return;
        }
    }

    if (load)
    {
        // TODO: make a global storage for this
        QueryResult* result;

        if (Instanceable())
        {
            result = CharacterDatabase.PQuery("SELECT `data` FROM `instance` WHERE `id` = '%u'", i_InstanceId);
        }
        else
        {
            result = CharacterDatabase.PQuery("SELECT `data` FROM `world` WHERE `map` = '%u'", GetId());
        }

        if (result)
        {
            Field* fields = result->Fetch();
            const char* data = fields[0].GetString();
            if (data)
            {
                DEBUG_LOG("Loading instance data for `%s` (Map: %u Instance: %u)", sScriptMgr.GetScriptName(i_script_id), GetId(), i_InstanceId);
                i_data->Load(data);
            }
            delete result;
        }
        else
        {
            // for non-instanceable map always add data to table if not found, later code expected that for map in `word` exist always after load
            if (!Instanceable())
            {
                CharacterDatabase.PExecute("INSERT INTO `world` VALUES ('%u', '')", GetId());
            }
        }
    }
    else
    {
        DEBUG_LOG("New instance data, \"%s\" ,initialized!", sScriptMgr.GetScriptName(i_script_id));
        i_data->Initialize();
    }
#endif
}

void Map::TeleportAllPlayersTo(TeleportLocation loc)
{
    while (HavePlayers())
    {
#if 0
        if (battle::object::Player* plr = m_mapRefManager.getFirst()->getSource())
        {
            // Teleport to specified location and removes the player from this map (if the map exists).
            // Todo : we can add some specific location if needed (ex: map exit location for dungeon)
            switch (loc)
            {
            case TELEPORT_LOCATION_HOMEBIND:
                plr->TeleportToHomebind();
                break;
            case TELEPORT_LOCATION_BG_ENTRY_POINT:
                plr->TeleportToBGEntryPoint();
                break;
            default:
                break;
            }
            // just in case, remove the player from the list explicitly here as well to prevent a possible infinite loop
            // note that this remove is not needed if the code works well in other places
            plr->GetMapRef().unlink();
        }
#endif
    }
}

void Map::SetWeather(unsigned int zoneId, WeatherType type, float grade, bool permanently)
{
    game::system::Weather* wth = m_weatherSystem->FindOrCreateWeather(zoneId);
    wth->SetWeather(WeatherType(type), grade, this, permanently);
}


template void Map::Add(battle::object::Corpse*);
template void Map::Add(battle::object::Creature*);
template void Map::Add(battle::object::GameObject*);
template void Map::Add(battle::object::DynamicObject*);

template void Map::Remove(battle::object::Corpse*, bool);
template void Map::Remove(battle::object::Creature*, bool);
template void Map::Remove(battle::object::GameObject*, bool);
template void Map::Remove(battle::object::DynamicObject*, bool);

bool Map::CanEnter(battle::object::Player* player)
{
#if 0 
    if (player->GetMapRef().getTarget() == this)
    {
        if (player->GetTransport())
        {
            return true;
        }
        else
        {
            sLog.outError("Map::CanEnter -%s already in map!", player->GetGuidStr().c_str());
            CFT_ASSERT(false);
            return false;
        }
    }
#endif

    return true;
}

/// Put scripts in the execution queue
bool Map::ScriptsStart(game::script::DBScriptType type, unsigned int id, battle::object::Object* source, battle::object::Object* target, ScriptExecutionParam execParams /*=SCRIPT_EXEC_PARAM_UNIQUE_BY_SOURCE_TARGET*/)
{
    CFT_ASSERT(source);

    ///- Find the script chain map
    auto scm = game::script::ScriptMgr::Instance().GetScriptChainMap(type);
    if (!scm)
    {
        return false;
    }

    auto s = scm->find(id);
    if (s == scm->end())
    {
        return false;
    }

    // prepare static data
    ObjectGuid sourceGuid = source->GetObjectGuid();
    ObjectGuid targetGuid = target ? target->GetObjectGuid() : ObjectGuid();
    ObjectGuid ownerGuid = source->isType(TYPEMASK_ITEM) ? ((battle::object::Item*)source)->GetOwnerGuid() : ObjectGuid();

    if (execParams)                                         // Check if the execution should be uniquely
    {
        for (ScriptScheduleMap::const_iterator searchItr = m_scriptSchedule.begin(); searchItr != m_scriptSchedule.end(); ++searchItr)
        {
            if (searchItr->second.IsSameScript(type, id,
                (execParams & SCRIPT_EXEC_PARAM_UNIQUE_BY_SOURCE) ? sourceGuid : ObjectGuid(),
                (execParams & SCRIPT_EXEC_PARAM_UNIQUE_BY_TARGET) ? targetGuid : ObjectGuid(), ownerGuid))
            {
#if 0
                cftf::loger::SysLog::Instance().Warning(std::format("DB-SCRIPTS: Process table `dbscripts [type={}]` id {}. Skip script as script already started for source {}, target {} - ScriptsStartParams {}", type, id, sourceGuid.GetString().c_str(), targetGuid.GetString().c_str(), execParams));
#endif
                return true;
            }
        }
    }

    ///- Schedule script execution for all scripts in the script map
    auto s2 = &(s->second);
    for (auto iter = s2->begin(); iter != s2->end(); ++iter)
    {
        game::script::ScriptAction sa(type, this, sourceGuid, targetGuid, ownerGuid, &(*iter));

        m_scriptSchedule.insert(ScriptScheduleMap::value_type(time_t(World::Instance().GetGameTime() + iter->delay), sa));

        game::script::ScriptMgr::Instance().IncreaseScheduledScriptsCount();
    }

    return true;
}

void Map::ScriptCommandStart(game::script::ScriptInfo const& script, unsigned int delay, battle::object::Object* source, battle::object::Object* target)
{
    // NOTE: script record _must_ exist until command executed

    // prepare static data
    ObjectGuid sourceGuid = source->GetObjectGuid();
    ObjectGuid targetGuid = target ? target->GetObjectGuid() : ObjectGuid();
    ObjectGuid ownerGuid = source->isType(TYPEMASK_ITEM) ? ((battle::object::Item*)source)->GetOwnerGuid() : ObjectGuid();

    game::script::ScriptAction sa(game::script::DBS_INTERNAL, this, sourceGuid, targetGuid, ownerGuid, &script);

    m_scriptSchedule.insert(ScriptScheduleMap::value_type(time_t(World::Instance().GetGameTime() + delay), sa));

    game::script::ScriptMgr::Instance().IncreaseScheduledScriptsCount();
}

/// Process queued scripts
void Map::ScriptsProcess()
{
    if (m_scriptSchedule.empty())
    {
        return;
    }
#if 0
    ///- Process overdue queued scripts
    ScriptScheduleMap::iterator iter = m_scriptSchedule.begin();
    // ok as multimap is a *sorted* associative container
    while (!m_scriptSchedule.empty() && (iter->first <= sWorld.GetGameTime()))
    {
        if (iter->second.HandleScriptStep())
        {
            // Terminate following script steps of this script
            DBScriptType type = iter->second.GetType();
            unsigned int id = iter->second.GetId();
            ObjectGuid sourceGuid = iter->second.GetSourceGuid();
            ObjectGuid targetGuid = iter->second.GetTargetGuid();
            ObjectGuid ownerGuid = iter->second.GetOwnerGuid();

            for (ScriptScheduleMap::iterator rmItr = m_scriptSchedule.begin(); rmItr != m_scriptSchedule.end();)
            {
                if (rmItr->second.IsSameScript(type, id, sourceGuid, targetGuid, ownerGuid))
                {
                    m_scriptSchedule.erase(rmItr++);
                    sScriptMgr.DecreaseScheduledScriptCount();
                }
                else
                {
                    ++rmItr;
                }
            }
        }
        else
        {
            m_scriptSchedule.erase(iter);

            sScriptMgr.DecreaseScheduledScriptCount();
        }
        iter = m_scriptSchedule.begin();
    }
#endif
}
/**
 * Function return player that in world at CURRENT map
 *
 * Note: This is function preferred if you sure that need player only placed at specific map
 *       This is not true for some spell cast targeting and most packet handlers
 *
 * @param guid must be player guid (HIGHGUID_PLAYER)
 */
battle::object::Player* Map::GetPlayer(ObjectGuid guid)
{
    auto plr = battle::object::ObjectAccessor::Instance().FindPlayer(guid);         // return only in world players
    return plr && plr->GetMap() == this ? plr : NULL;
}

/**
 * Function return creature (non-pet and then most summoned by spell creatures) that in world at CURRENT map
 *
 * @param guid must be creature guid (HIGHGUID_UNIT)
 */
battle::object::Creature* Map::GetCreature(ObjectGuid guid)
{
    return m_objectsStore.Find(guid, (battle::object::Creature*)nullptr);
}

/**
 * Function return pet that in world at CURRENT map
 *
 * @param guid must be pet guid (HIGHGUID_PET)
 */
battle::object::Pet* Map::GetPet(ObjectGuid guid)
{
    return m_objectsStore.Find(guid, (battle::object::Pet*)nullptr);
}

/**
 * Function return corpse that at CURRENT map
 *
 * Note: corpse can be NOT IN WORLD, so can't be used corpse->GetMap() without pre-check corpse->isInWorld()
 *
 * @param guid must be corpse guid (HIGHGUID_CORPSE)
 */
battle::object::Corpse* Map::GetCorpse(ObjectGuid guid)
{
#if 1
    return nullptr;
#else
    Corpse* ret = sObjectAccessor.GetCorpseInMap(guid, GetId());
    return ret && ret->GetInstanceId() == GetInstanceId() ? ret : NULL;
#endif
}

/**
 * Function return non-player unit object that in world at CURRENT map, so creature, or pet
 *
 * @param guid must be non-player unit guid (HIGHGUID_PET HIGHGUID_UNIT)
 */
battle::object::Creature* Map::GetAnyTypeCreature(ObjectGuid guid)
{
    switch (guid.GetHigh())
    {
    case HIGHGUID_UNIT:         return GetCreature(guid);
    case HIGHGUID_PET:          return GetPet(guid);
    default:                    break;
    }

    return nullptr;
}

/**
 * Function return gameobject that in world at CURRENT map
 *
 * @param guid must be gameobject guid (HIGHGUID_GAMEOBJECT)
 */
battle::object::GameObject* Map::GetGameObject(ObjectGuid guid)
{
    return m_objectsStore.Find(guid, (battle::object::GameObject*)nullptr);
}

/**
 * Function return dynamic object that in world at CURRENT map
 *
 * @param guid must be dynamic object guid (HIGHGUID_DYNAMICOBJECT)
 */
battle::object::DynamicObject* Map::GetDynamicObject(ObjectGuid guid)
{
    return m_objectsStore.Find(guid, (battle::object::DynamicObject*)nullptr);
}

/**
 * Function return unit in world at CURRENT map
 *
 * Note: in case player guid not always expected need player at current map only.
 *       For example in spell casting can be expected any in world player targeting in some cases
 *
 * @param guid must be unit guid (HIGHGUID_PLAYER HIGHGUID_PET HIGHGUID_UNIT)
 */
battle::object::Unit* Map::GetUnit(ObjectGuid guid)
{
    if (guid.IsPlayer())
    {
        return GetPlayer(guid);
    }

    return GetAnyTypeCreature(guid);
}

/**
 * Function return world object in world at CURRENT map, so any except transports
 */
battle::object::WorldObject* Map::GetWorldObject(ObjectGuid guid)
{
    switch (guid.GetHigh())
    {
    case HIGHGUID_PLAYER:       return GetPlayer(guid);
    case HIGHGUID_GAMEOBJECT:   return GetGameObject(guid);
    case HIGHGUID_UNIT:         return GetCreature(guid);
    case HIGHGUID_PET:          return GetPet(guid);
    case HIGHGUID_DYNAMICOBJECT: return GetDynamicObject(guid);
    case HIGHGUID_CORPSE:
    {
        // corpse special case, it can be not in world
        battle::object::Corpse* corpse = GetCorpse(guid);
        return corpse && corpse->IsInWorld() ? corpse : nullptr;
    }
    case HIGHGUID_MO_TRANSPORT:
    case HIGHGUID_TRANSPORT:
    default:                    break;
    }

    return nullptr;
}

void Map::SendObjectUpdates()
{
#if 0
    UpdateDataMapType update_players;

    while (!i_objectsToClientUpdate.empty())
    {
        Object* obj = *i_objectsToClientUpdate.begin();
        i_objectsToClientUpdate.erase(i_objectsToClientUpdate.begin());
        obj->BuildUpdateData(update_players);
    }

    WorldPacket packet;                                     // here we allocate a std::vector with a size of 0x10000
    for (UpdateDataMapType::iterator iter = update_players.begin(); iter != update_players.end(); ++iter)
    {
        iter->second.BuildPacket(&packet);
        iter->first->GetSession()->SendPacket(&packet);
        packet.clear();                                     // clean the string
    }
#endif

}

unsigned int Map::GenerateLocalLowGuid(HighGuid guidhigh)
{
    // TODO: for map local guid counters possible force reload map instead shutdown server at guid counter overflow
    switch (guidhigh)
    {
    case HIGHGUID_UNIT:
        return m_CreatureGuids.Generate();
    case HIGHGUID_GAMEOBJECT:
        return m_GameObjectGuids.Generate();
    case HIGHGUID_DYNAMICOBJECT:
        return m_DynObjectGuids.Generate();
    case HIGHGUID_PET:
        return m_PetGuids.Generate();
    default:
        CFT_ASSERT(false);
        return 0;
    }
}

#if 0
/**
 * Helper structure for building static chat information
 *
 */
class StaticMonsterChatBuilder
{
public:
    StaticMonsterChatBuilder(CreatureInfo const* cInfo, ChatMsg msgtype, int32 textId, Language language, Unit const* target, unsigned int senderLowGuid = 0)
        : i_cInfo(cInfo), i_msgtype(msgtype), i_textId(textId), i_language(language), i_target(target)
    {
        // 0 lowguid not used in core, but accepted fine in this case by client
        i_senderGuid = i_cInfo->GetObjectGuid(senderLowGuid);
    }
    void operator()(WorldPacket& data, int32 loc_idx)
    {
        char const* text = sObjectMgr.GetMangosString(i_textId, loc_idx);

        char const* nameForLocale = i_cInfo->Name;
        sObjectMgr.GetCreatureLocaleStrings(i_cInfo->Entry, loc_idx, &nameForLocale);

        ChatHandler::BuildChatPacket(data, i_msgtype, text, i_language, CHAT_TAG_NONE, i_senderGuid, nameForLocale, i_target ? i_target->GetObjectGuid() : ObjectGuid(),
            i_target ? i_target->GetNameForLocaleIdx(loc_idx) : "");
    }

private:
    ObjectGuid i_senderGuid;
    CreatureInfo const* i_cInfo;
    ChatMsg i_msgtype;
    int32 i_textId;
    Language i_language;
    Unit const* i_target;
};
#endif

/**
 * Function simulates yell of creature
 *
 * @param guid must be creature guid of whom to Simulate the yell, non-creature guids not supported at this moment
 * @param textId Id of the simulated text
 * @param language language of the text
 * @param target, can be NULL
 */
void Map::MonsterYellToMap(ObjectGuid guid, int textId, Language language, battle::object::Unit const* target) const
{
    if (guid.IsAnyTypeCreature())
    {
        mt::CreatureInfo const* cInfo = mt::CreatureInfo::GetElement(guid.GetEntry());
        if (!cInfo)
        {
            cftf::loger::SysLog::Instance().Error(std::format("Map::MonsterYellToMap: Called for nonexistent creature entry in guid: {}", guid.GetString().c_str()));
            return;
        }

        MonsterYellToMap(cInfo, textId, language, target, guid.GetCounter());
    }
    else
    {
        cftf::loger::SysLog::Instance().Error(std::format("Map::MonsterYellToMap: Called for non creature guid: {}", guid.GetString().c_str()));
        return;
    }
}

/**
 * Function simulates yell of creature
 *
 * @param cinfo must be entry of Creature of whom to Simulate the yell
 * @param textId Id of the simulated text
 * @param language language of the text
 * @param target, can be NULL
 * @param senderLowGuid provide way proper show yell for near spawned creature with known lowguid,
 *        0 accepted by client else if this not important
 */

void Map::MonsterYellToMap(mt::CreatureInfo const* cinfo, int textId, Language language, battle::object::Unit const* target, unsigned int senderLowGuid /*= 0*/) const
{
#if 0
    StaticMonsterChatBuilder say_build(cinfo, CHAT_MSG_MONSTER_YELL, textId, language, target, senderLowGuid);
    MaNGOS::LocalizedPacketDo<StaticMonsterChatBuilder> say_do(say_build);

    Map::PlayerList const& pList = GetPlayers();
    for (PlayerList::const_iterator itr = pList.begin(); itr != pList.end(); ++itr)
    {
        say_do(itr->getSource());
    }
#endif
}


/**
 * Function to play sound to all players in map
 *
 * @param soundId Played Sound
 * @param zoneId Id of the Zone to which the sound should be restricted
 */
void Map::PlayDirectSoundToMap(unsigned int soundId, unsigned int zoneId /*=0*/) const
{
#if 0
    WorldPacket data(SMSG_PLAY_SOUND, 4);
    data << unsigned int(soundId);

    Map::PlayerList const& pList = GetPlayers();
    for (PlayerList::const_iterator itr = pList.begin(); itr != pList.end(); ++itr)
        if (!zoneId || itr->getSource()->GetZoneId() == zoneId)
        {
            itr->getSource()->SendDirectMessage(&data);
        }
#endif
}

/**
 * Function to check if a point is in line of sight from an other point
 */
bool Map::IsInLineOfSight(float srcX, float srcY, float srcZ, float destX, float destY, float destZ) const
{
#if 1
    return true;
#else
    return VMAP::VMapFactory::createOrGetVMapManager()->isInLineOfSight(GetId(), srcX, srcY, srcZ, destX, destY, destZ)
        && m_dyn_tree.isInLineOfSight(srcX, srcY, srcZ, destX, destY, destZ);
#endif
}

/**
 * get the hit position and return true if we hit something (in this case the dest position will hold the hit-position)
 * otherwise the result pos will be the dest pos
 */
bool Map::GetHitPosition(float srcX, float srcY, float srcZ, float& destX, float& destY, float& destZ, float modifyDist) const
{
#if 1
    return true;
#else;
    // at first check all static objects
    float tempX, tempY, tempZ = 0.0f;
    bool result0 = VMAP::VMapFactory::createOrGetVMapManager()->getObjectHitPos(GetId(), srcX, srcY, srcZ, destX, destY, destZ, tempX, tempY, tempZ, modifyDist);
    if (result0)
    {
        DEBUG_LOG("Map::GetHitPosition vmaps corrects gained with static objects! new dest coords are X:%f Y:%f Z:%f", destX, destY, destZ);
        destX = tempX;
        destY = tempY;
        destZ = tempZ;
    }
    // at second all dynamic objects, if static check has an hit, then we can calculate only to this closer point
    bool result1 = m_dyn_tree.getObjectHitPos(srcX, srcY, srcZ, destX, destY, destZ, tempX, tempY, tempZ, modifyDist);
    if (result1)
    {
        DEBUG_LOG("Map::GetHitPosition vmaps corrects gained with dynamic objects! new dest coords are X:%f Y:%f Z:%f", destX, destY, destZ);
        destX = tempX;
        destY = tempY;
        destZ = tempZ;
    }
    return result0 || result1;
#endif
}

// Find an height within a reasonable range of provided Z. This method may fail so we have to handle that case.
bool Map::GetHeightInRange(float x, float y, float& z, float maxSearchDist /*= 4.0f*/) const
{
#if 0
    float height, vmapHeight, mapHeight;
    vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
    mapHeight = INVALID_HEIGHT_VALUE;

    VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
    if (!vmgr->isLineOfSightCalcEnabled())
    {
        vmgr = NULL;
    }

    if (vmgr)
    {
        // pure vmap search
        vmapHeight = vmgr->getHeight(i_id, x, y, z + 2.0f, maxSearchDist + 2.0f);
    }

    // find raw height from .map file on X,Y coordinates
    if (GridMap* gmap = const_cast<TerrainInfo*>(m_TerrainData)->GetGrid(x, y)) // TODO:: find a way to remove that const_cast
    {
        mapHeight = gmap->getHeight(x, y);
    }

    float diffMaps = fabs(fabs(z) - fabs(mapHeight));
    float diffVmaps = fabs(fabs(z) - fabs(vmapHeight));
    if (diffVmaps < maxSearchDist)
    {
        if (diffMaps < maxSearchDist)
        {
            // well we simply have to take the highest as normally there we cannot be on top of cavern is maxSearchDist is not too big
            if (vmapHeight > mapHeight)
            {
                height = vmapHeight;
            }
            else
            {
                height = mapHeight;
            }

            //sLog.outString("vmap %5.4f, map %5.4f, height %5.4f", vmapHeight, mapHeight, height);
        }
        else
        {
            //sLog.outString("vmap %5.4f", vmapHeight);
            height = vmapHeight;
        }
    }
    else
    {
        if (diffMaps < maxSearchDist)
        {
            //sLog.outString("map %5.4f", mapHeight);
            height = mapHeight;
        }
        else
        {
            return false;
        }
    }

    z = std::max<float>(height, m_dyn_tree.getHeight(x, y, height + 1.0f, maxSearchDist));
#endif
    return true;
}

float Map::GetHeight(float x, float y, float z) const
{
    float staticHeight = m_TerrainData->GetHeightStatic(x, y, z);

    // Get Dynamic Height around static Height (if valid)
    float dynSearchHeight = 2.0f + (z < staticHeight ? staticHeight : z);
    return std::max<float>(staticHeight, m_dyn_tree.getHeight(x, y, dynSearchHeight, dynSearchHeight - staticHeight));
}

void Map::InsertGameObjectModel(const GameObjectModel& mdl)
{
    m_dyn_tree.insert(mdl);
}

void Map::RemoveGameObjectModel(const GameObjectModel& mdl)
{
    m_dyn_tree.remove(mdl);
}

bool Map::ContainsGameObjectModel(const GameObjectModel& mdl) const
{
    return m_dyn_tree.contains(mdl);
}
// This will generate a random point to all directions in water for the provided point in radius range.
bool Map::GetRandomPointUnderWater(float& x, float& y, float& z, float radius, GridMapLiquidData& liquid_status)
{
#if 1
    return true;
#else
    const float angle = rand_norm_f() * (M_PI_F * 2.0f);
    const float range = rand_norm_f() * radius;

    float i_x = x + range * cos(angle);
    float i_y = y + range * sin(angle);

    // get real ground of new point
    // the code consider cylinder instead of sphere for possible z
    float ground = GetHeight(i_x, i_y, z);
    if (ground > INVALID_HEIGHT) // GetHeight can fail
    {
        float min_z = z - 0.7f * radius; // 0.7 to have a bit a "flat" cylinder, TODO which value looks nicest
        if (min_z < ground)
        {
            min_z = ground + 0.5f; // Get some space to prevent under map
        }

        float liquidLevel = liquid_status.level - 2.0f; // just to make the generated point is in water and not on surface or a bit above

        // if not enough space to fit the creature better is to return from here
        if (min_z > liquidLevel)
        {
            return false;
        }

        float max_z = std::max(z + 0.7f * radius, min_z);
        max_z = std::min(max_z, liquidLevel);
        x = i_x;
        y = i_y;
        z = min_z + rand_norm_f() * (max_z - min_z);
        return true;
    }
    return false;
#endif
}

// This will generate a random point to all directions in air for the provided point in radius range.
bool Map::GetRandomPointInTheAir(float& x, float& y, float& z, float radius)
{
    const float angle = rand_norm_f() * (cftc::CFT_PI * 2.0f);
    const float range = rand_norm_f() * radius;

    float i_x = x + range * cos(angle);
    float i_y = y + range * sin(angle);

    // get real ground of new point
    // the code consider cylinder instead of sphere for possible z
    float ground = GetHeight(i_x, i_y, z);
    if (ground > INVALID_HEIGHT) // GetHeight can fail
    {
        float min_z = z - 0.7f * radius; // 0.7 to have a bit a "flat" cylinder, TODO which value looks nicest
        if (min_z < ground)
        {
            min_z = ground + 2.5f; // Get some space to prevent landing
        }
        float max_z = std::max(z + 0.7f * radius, min_z);
        x = i_x;
        y = i_y;
        z = min_z + rand_norm_f() * (max_z - min_z);
        return true;
    }
    return false;
}

// supposed to be used for not big radius, usually less than 20.0f
bool Map::GetReachableRandomPointOnGround(float& x, float& y, float& z, float radius)
{
    // Generate a random range and direction for the new point
    const float angle = rand_norm_f() * (cftc::CFT_PI * 2.0f);
    const float range = rand_norm_f() * radius;

    float i_x = x + range * cos(angle);
    float i_y = y + range * sin(angle);
    float i_z = z + 1.0f;

    GetHitPosition(x, y, z + 1.0f, i_x, i_y, i_z, -0.5f);
    i_z = z; // reset i_z to z value to avoid too much difference from original point before GetHeightInRange
    if (!GetHeightInRange(i_x, i_y, i_z)) // GetHeight can fail
    {
        return false;
    }

    // here we have a valid position but the point can have a big Z in some case
    // next code will check angle from 2 points of view: x-axis and y-axis movement
    //        c
    //       /|
    //      / |
    //    b/__|a

    // project vector to get only positive value
    float ac = fabs(z - i_z);
    float delta = 0;

    // slope represented by b angle (in radian)
    float slope = 0;
    const float MAX_SLOPE_IN_RADIAN = 50.0f / 180.0f * cftc::CFT_PI;  // 50(degree) max seem best value for walkable slope

    delta = fabs(x - i_x);  // check x-axis movement
    if (delta > 0.0f)       // check to avoid divide by 0
    {
        // compute slope
        float slope = atan(ac / delta);
        if (slope < MAX_SLOPE_IN_RADIAN)
        {
            x = i_x;
            y = i_y;
            z = i_z;
            return true;
        }
    }

    delta = fabs(y - i_y);  // check y-axis movement
    if (delta > 0.0f)       // check to avoid divide by 0
    {
        // compute slope
        slope = atan(ac / delta);
        if (slope < MAX_SLOPE_IN_RADIAN)
        {
            x = i_x;
            y = i_y;
            z = i_z;
            return true;
        }
    }

    return false;
}

// Get random point by handling different situation depending of if the unit is flying/swimming/walking
bool Map::GetReachableRandomPosition(battle::object::Unit* unit, float& x, float& y, float& z, float radius)
{
    float i_x = x;
    float i_y = y;
    float i_z = z;

    bool isFlying;
    bool isSwimming = true;
    switch (unit->GetTypeId())
    {
    case TYPEID_PLAYER:
        isFlying = static_cast<battle::object::Player*>(unit)->IsFlying();
        break;
    case TYPEID_UNIT:
        isFlying = static_cast<battle::object::Creature*>(unit)->IsFlying();
        isSwimming = static_cast<battle::object::Creature*>(unit)->IsSwimming();
        break;
    default:
        cftf::loger::SysLog::Instance().Error(std::format("Map::GetReachableRandomPosition> Unsupported unit ({}) is passed!", unit->GetGuidStr().c_str()));
        return false;
    }

    if (radius < 0.1f)
    {
        cftf::loger::SysLog::Instance().Error(std::format("Map::GetReachableRandomPosition> Invalid radius ({}) for {}", radius, unit->GetGuidStr().c_str()));
        return false;
    }

    bool newDestAssigned;
    if (isFlying)
    {
        newDestAssigned = GetRandomPointInTheAir(i_x, i_y, i_z, radius);
    }
    else
    {
        GridMapLiquidData liquid_status;
        GridMapLiquidStatus res = m_TerrainData->getLiquidStatus(i_x, i_y, i_z, MAP_ALL_LIQUIDS, &liquid_status);
        if (isSwimming && (res & (LIQUID_MAP_UNDER_WATER | LIQUID_MAP_IN_WATER)))
        {
            newDestAssigned = GetRandomPointUnderWater(i_x, i_y, i_z, radius, liquid_status);
        }
        else
        {
            newDestAssigned = GetReachableRandomPointOnGround(i_x, i_y, i_z, radius);
        }
    }

    if (newDestAssigned)
    {
        x = i_x;
        y = i_y;
        z = i_z;
        return true;
    }

    return false;
}

void Map::LoadLocalTransports()
{
#if 0
    //load local transports for this map
    std::pair<LocalTransportGuidsOnMap::const_iterator, LocalTransportGuidsOnMap::const_iterator> bounds = sObjectMgr.GetLocalTransportGuids()->equal_range(GetId());
    for (LocalTransportGuidsOnMap::const_iterator itr = bounds.first; itr != bounds.second; ++itr)
    {
        LocalTransport* lt = new LocalTransport();
        if (lt->Initialize(itr->second, this))
        {
            i_transports.insert(lt);
        }
        else
        {
            delete lt;
        }
    }
#endif
#if 0
    sLog.outString();
#endif
    /*
        for (std::set<Transport*>::const_iterator i = i_transports.begin(); i != i_transports.end(); ++i)
        {
            sLog.outString(">>>%s initialized", (*i)->GetGuidStr().c_str());
        }
    */

    if (GetId() == 369)
    {
        cftf::loger::SysLog::Instance().Deubg(std::format(">> Loaded {} tram cars for map {}", i_transports.size(), GetId()));
    }
    else
    {
        cftf::loger::SysLog::Instance().Deubg(std::format(">> Loaded {} local transports for map {}", i_transports.size(), GetId()));
    }
}